package cn.zzz.openplatform.common.selector;

import cn.zzz.openplatform.common.model.OpenApiCredentials;

import java.util.List;

/**
 * 权重策略实现
 */
public class WeightedSelector implements CredentialSelector {
    @Override
    public <T extends OpenApiCredentials> T select(List<T> credentials) {
        double totalWeight = credentials.stream().mapToDouble(OpenApiCredentials::getWeight).sum();
        double randomPoint = Math.random() * totalWeight;
        double currentWeight = 0;
        for (T cred : credentials) {
            currentWeight += cred.getWeight();
            if (randomPoint <= currentWeight) return cred;
        }
        return credentials.get(0); // 兜底逻辑
    }
}